<?php
namespace app\models;

/**
 * @desc 采购入库model
 * @author liaojianwen
 * @date 2016-12-14
 */
 use app\enum\EnumOther;
 use app\models\BaseModel;
 use app\dao\PurchaseDAO;
 use app\dao\PurchaseDetailDAO;
 use app\dao\ProductDAO;
 use app\dao\TransactionDAO;
 use Yii;
 use app\dao\ProcurementDAO;
 use app\dao\ProcurementDetailDAO;
 use app\dao\StockPileDAO;
 use app\helpers\Utility;
 use app\enum\EnumOriginType;
 use app\dao\ProductUpdateLogDAO;
 use app\dao\PayablesDAO;
 use app\dao\WarehouseDAO;
use app\dao\AccountPriceLogDAO;
	
 class PurchaseModel extends BaseModel
 {
	/**
	 * @desc 覆盖父方法返回对象
	 * @author liaojianwen
	 * @date 2016-12-14
	 * @return PurchaseModel
	 */
 	public static function model($className=__CLASS__) {
 		return parent::model($className);
 	}
 	
 	/**
 	 * @desc 保存采购入库单据
 	 * @param [] $head 单头内容
 	 * @param [] $detail 明细内容
 	 * @param int $id 采购入库单内容
 	 * @author liaojianwen
 	 * @date 2016-12-14
 	 */
 	public function savePurchase($head, $detail, $remove, $id)
 	{
 		if(empty($head)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
 		}
 		if (empty ( $detail )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
 		}
 		if(empty($id)){
 			$id = 0;
 		}
 		
 		foreach ($head as $k =>$hed){
 			if(empty($hed)){
 				unset($head[$k]);
 			}
 		}
 		foreach ($detail as $k=> $det){
 			foreach ($det as $j => $deet){
 				if(empty($deet)){
 					unset($detail[$k][$j]);
 				}
 			}
 		}
 		// 表头信息
 		$head ['purchase_date'] = strtotime ( $head ['purchase_date'] );
 		$cond_head = "purchase_id =:id";
 		$param_head = [
 				':id' => $id
 		];
 		$Iid = PurchaseDAO::getInstance ()->ireplaceinto ( $head, $cond_head, $param_head, true );
 		if (! $Iid) {
 			$tr->rollBack();
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save purchase_head failure' );
 		}
 		// 表单明细
//  		PurchaseDetailDAO::getInstance()->iupdate(['delete_flag' => EnumOther::DELETED], "purchase_id =:did", [':did'=>$Iid]);// 先删除后没有删除的数据更新回来
 		foreach ($remove as $move){
 			$res_remove = PurchaseDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "purchase_det_id = :det_id", [':det_id'=>$move['purchase_det_id']]);
 			if(!$res_remove){
 				$tr->rollBack();
 				$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove purchase_det_id:'+$move['purchase_det_id'] +'failed');
 			}
 		}
 		foreach ( $detail as &$det ) {
 			$det ['purchase_id'] = $Iid;
 			$det ['delete_flag'] = EnumOther::NO_DELETE;
 			$cond_det = "purchase_id = :id and purchase_det_id = :lid";
 			$param_det = [
 					':id' => $Iid,
 					':lid' =>  isset($det ['purchase_det_id'])?$det['purchase_det_id']:0
 			];
//  			$det['received_quantity'] = $det['quantity'];//确认的时候写
			$det['minus_quantity'] = $det['base_quantity'];//未退数量
 			$res_det = PurchaseDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
 			if (! $res_det) {
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save purchase_detail failure' );
 			}
 		}
 		
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
 	}
 	
 	/**
 	 * @desc 获取采购入库单列表
 	 * @param [] $pageInfo 页面信息
 	 * @param [] $condition 查询信息 
 	 * @author liaojianwen
 	 * @date 2016-12-14
 	 */
 	public function getPurchases($pageInfo, $condition)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','pageInfo is empty');
 		}
 		$result = PurchaseDAO::getInstance()->getPurchases($condition, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	
 	/**
 	 * @desc 根据采购入库单id 获取入库单信息
 	 * @param int $id
 	 * @author liaojianwen
 	 * @date 2016-12-14
 	 */
 	public function getPurchaseInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$pur_head = PurchaseDAO::getInstance()->getPurchaseHead($id);
 		if(empty($pur_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$pur_det = PurchaseDetailDAO::getInstance()->getPurchaseDet($id);
 		if(empty($pur_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		$result['head'] = $pur_head;
 		$result['det'] = $pur_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 确认采购入库单
 	 * @author liaojianwen
 	 * @date 2016-12-14
 	 */
 	public function confirmPurchase($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$id = (int)$id;
 		$tr = Yii::$app->db->beginTransaction ();
 		try {
 			$re_confirm = PurchaseDAO::getInstance ()->updateByPk ( $id, [
 					'confirm_flag' => EnumOther::CONFIRM
 			] );
 			if (! $re_confirm) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'confirm fail' );
 			}
 			
 			//采购订单id
 			$select_arr = [
 				'purchase_id',
 				'purchase_no',
 				'procurement_id',
 				'vendor_id',
 				'purchase_date',
 				'purchase_amount',
 				'purchase_type',
 				'purchase_man',
 				'remark',
 			];
 			$pro_res = PurchaseDAO::getInstance()->iselect($select_arr, "purchase_id =:pid", [':pid'=>$id],'one');//['procurement_id']
 			$procurement_id = $pro_res['procurement_id'];
 			$fields = [
 					'h.purchase_no',
 					'd.goods_id',
 					'd.quantity',
 					'h.purchase_type',
 					'd.purchase_det_id',
 					'h.warehouse_id',
 					'd.procurement_det_id',
//  					'd.minus_quantity',
//  					'd.received_quantity',
 					'h.purchase_date',
 					'h.vendor_id',
 					'd.quantity_unit',
 					'd.purchase_det_id',
 					'd.base_quantity',
 					'd.base_unit',
 					'd.base_price',
 			];
 			$conditions = "d.purchase_id =:id and d.delete_flag = :flag";
 			$params = [
 					':id' => $id,
 					':flag' => EnumOther::NO_DELETE
 			];
 			$joinArray = [
 					[
 						'purchase h',
 						"h.purchase_id = d.purchase_id"
 					]
 			];
 			$purchase_det = PurchaseDetailDAO::getInstance ()->iselect ( $fields, $conditions, $params, 'all', 'd.purchase_det_id ASC', $joinArray, 'd' );
 			if (! $purchase_det) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select det fail' );
 			}
 			// 出入库明细
 			$finish_flag = 0;//采购订单整单是否完成的标记
 			foreach ( $purchase_det as $det ) {
 				$PRODUCT = ProductDAO::getInstance()->iselect(["price","quantity"], "product_id = :pid", [':pid'=>$det['goods_id']],'one');
 				if(isset($PRODUCT['price'])){
 					$price = $PRODUCT['price'];
 				} else {
 					$price = 0;
 				}
 				
 				$column_trans = array (
 						'goods_id' => $det ['goods_id'],
 						'quantity' => $det ['base_quantity'],
 						'quantity_unit' => $det['base_unit'],
 						'origin_type' => $det ['purchase_type'],
 						'origin_id' => $det ['purchase_no'],
 						'origin_line_id' => $det ['purchase_det_id'], // 原单序号
 						'origin_time'=> $det['purchase_date'],
 						'vendor_id'=> $det['vendor_id'],
 						'warehouse_id' => $det ['warehouse_id'],
 						'init_num' => $PRODUCT['quantity'],//上期数量
 						'flag' => EnumOther::IN_FLAG
 				);
 		
 				$res_trans = TransactionDAO::getInstance ()->iinsert ( $column_trans, true );
 				if (! $res_trans) {
 					$tr->rollBack ();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save transaction failure' );
 				}
 		
 				
 				//商品成本价计算 --start
 				$priceRes = $this->AccountingPrice($det['goods_id'], $det['base_quantity'], $det['base_price'], true, EnumOriginType::origin_income);
 				if(!$priceRes){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'accounting price fail');
 				}
 				//////////////////-----end

//  			更新product quantity 加库存
 				$WAREHOUSE = WarehouseDAO::getInstance()->iselect("is_scrapped,warehouse_name", "warehouse_id =:wid", [':wid'=>$det['warehouse_id']],'one');
				if(isset($WAREHOUSE['is_scrapped'])){
					if($WAREHOUSE['is_scrapped'] != '1'){//不是报废单
		 				$pro_select = ProductDAO::getInstance ()->updateAllCounters ( [
		 						'quantity' => $det ['base_quantity'],
		 						'amount'=> $price * $det['base_quantity'],
		 				], "product_id =:id", [
		 						':id' => $det ['goods_id']
		 				] );
		 		
		 				if (! $pro_select) {
		 					$tr->rollBack ();
		 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
		 				}
		 			}
		 		} else {
					$tr->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','select scrapped failed');
				}
 				
 				//product_update_log 商品更新记录//
 				$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $det['purchase_type']);
 				
 				$log_columns = [
 						'product_id' => $det ['goods_id'],
 						'update_num' => $det ['base_quantity'],
 						'num_unit' => $det['base_unit'],
 						'origin_id' => $id,
 						'origin_no' => $det['purchase_no'],
 						'origin_line_id'=> $det['purchase_det_id'],
 						'origin_type'=> $det['purchase_type'],
 					    'update_time'=>strtotime(date('Y-m-d')),
 						'flag'=> EnumOther::IN_FLAG,
 						'initial_num'=> $PRODUCT['quantity'],//上期数量
 						'remark'=> $_order_type .($WAREHOUSE['warehouse_name']?:''). EnumOther::PLUS,
 						'warehouse_id' => $det['warehouse_id'],
 						'create_man' => Yii::$app->user->id,
 				];
 				$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 				if(! $res_log){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 				}
 				
 				//采购订单表回写//是由导入采购订单的入库单才要执行下面代码
 				if($procurement_id){
	 				$pro_finish = ProcurementDetailDAO::getInstance()->updateFinish($procurement_id,$det);
	 				if($pro_finish['Ack'] == 'error'){
	 					$tr->rollBack();
	 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$pro_finish['msg']);
	 				}
 				}
 				
 				
 				//分仓列表数据的插入或者更新--start
 				$stock_conditions = "warehouse_id =:wid and product_id=:pid and delete_flag =:flag";
 				$stock_params = [
 						':wid'=>$det['warehouse_id'],
						':pid' => $det ['goods_id'],
						':flag' => EnumOther::NO_DELETE 
				];
				$stock_select = StockPileDAO::getInstance ()->iselect ( "stock_pile_id", $stock_conditions, $stock_params, 'one' );
				if (! $stock_select) {
					// 没有数据，插入新数据 //入库
					
					$stock_columns = [ 
							'warehouse_id' => $det ['warehouse_id'],
							'product_id' => $det ['goods_id'],
							'quantity' => $det ['base_quantity'],
							'quantity_unit' => $det ['base_unit'] 
					];
					$stock_insert = StockPileDAO::getInstance ()->iinsert ( $stock_columns, true );
					if (! $stock_insert) {
						$tr->rollBack ();
						return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'insert stock pile failure' );
					}
 				} else {
 					//有数据，更新数据
 					$stock_update = StockPileDAO::getInstance()->updateAllCounters(['quantity'=> $det['base_quantity']], $stock_conditions, $stock_params);
 					if(! $stock_update){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','update stock pile failure');
 					}
 				}
 				//分仓 --end
 				
 				//应付单数据表数据插入 --start
 					$column_pay = [
 						'origin_id' => $pro_res['purchase_id'],
 						'origin_no' => $pro_res['purchase_no'],
 						'origin_type' => $pro_res['purchase_type'],
 						'pay_time' => $pro_res['purchase_date'],
 						'pay_type'=> EnumOriginType::origin_purchase_pay,
 						'vendor_id' => $pro_res['vendor_id'],
 						'pay_man' => $pro_res['purchase_man'],
 						'pay_amount' => $pro_res['purchase_amount'],
 						'settle_amount' => $pro_res['purchase_amount'],
 						'left_amount' => $pro_res['purchase_amount'],
 						'description' => '应付账单，采购入库单',
 						'remark'=> $pro_res['remark'],
 						'create_man' => Yii::$app->user->id,
 							
 					];
 					$cond = "origin_id = :oid and delete_flag = :flag";
 					$param =[
 						':oid'=> $pro_res['purchase_id'],
 						':flag'=> EnumOther::NO_DELETE,
 					];
 					$res_pay = PayablesDAO::getInstance()->ireplaceinto($column_pay, $cond, $param,true);
 					if(! $res_pay){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'insert payables fail');
 					}
 				//应付单 --end
 				
 			}

 			$tr->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tr->rollBack ();
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 删除
 	 * @author liaojianwen
 	 * @date 2016-12-14
 	 */
 	public function delPurchase($ids)
 	{
 		if(empty($ids)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$_ids = explode ( ',', $ids );
 		
 		$tT = Yii::$app->db->beginTransaction ();
 		try {
 			foreach ( $_ids as $id ) {
 				$res_purchase = PurchaseDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
 				if(!$res_purchase){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_purchase fail');
 				}
 				//purchase_detail
 				$purchase_det = PurchaseDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "purchase_id=:id", [':id'=>$id]);
 				if(!$purchase_det){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_purchase_det fail');
 				}
//  				//删除生成的采购应付
//  				$res_payable = PayablesDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "origin_id =:oid", [':oid'=>$id]);
//  				if(!$res_payable){
//  					$tT->rollBack();
//  					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'delete payable failed');
//  				}
 				$procurement_id = 0;
 				//更新product_quantity
 				$fields = [
 						't.goods_id',
 						't.quantity',
 						't.transaction_id',
 						'i.warehouse_id',
 						'i.purchase_no',
 						'd.quantity_unit',
 						'i.purchase_type',
 						'd.purchase_det_id',
 						'i.procurement_id',
 						'd.procurement_det_id'
 				];
 				$conditions = "t.delete_flag = :flag";
 				$params = [
 						':flag'=>EnumOther::NO_DELETE,
 				];
 				$joinArray = [
 						[
 								'purchase i',
 								'i.purchase_no = t.origin_id and i.purchase_id = '.$id,
 								'right'=>'',
 						],
 						[
 								'purchase_detail d',
 								'd.purchase_det_id = t.origin_line_id',
 								'left'=>''
 						]
 						
 				];
 				$trans_select = TransactionDAO::getInstance()->iselect($fields, $conditions, $params,'all',"t.create_time ASC",$joinArray,'t');
 				if (! empty ( $trans_select )) {
 					// 已确认的入库单才有transtions,减库存
 					foreach ( $trans_select as $trans ) {
 						
 						$procurement_id = $trans['procurement_id'];
 						//记录更新product 前的quantity
 						$PRODUCT = ProductDAO::getInstance()->iselect("quantity", "product_id = :pid", [':pid'=>$trans['goods_id']],'one');
 						//更新product quantity
 						$pro_minus = ProductDAO::getInstance ()->updateAllCounters ( [
 								'quantity' => - $trans ['quantity'],
 						], "product_id =:id", [
 								':id' => $trans ['goods_id']
 						] );
 							
 						if (! $pro_minus) {
 							$tT->rollBack();
 							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
 						}
 		

 						//product_update_log 商品更新记录
 						$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $trans['purchase_type']);
 						
 						$log_columns = [
 								'product_id' => $trans ['goods_id'],
 								'update_num' => $trans ['quantity'],
 								'num_unit' => $trans['quantity_unit'],
 								'origin_id' => $id,
 								'origin_no' => $trans['purchase_no'],
 								'origin_line_id'=> $trans['purchase_det_id'],
 								'origin_type'=> $trans['purchase_type'],
 								'update_time'=>strtotime(date('Y-m-d')),
 								'flag'=> EnumOther::OUT_FLAG,
 								'initial_num'=> $PRODUCT['quantity'],//上期数量
 								'remark'=> $_order_type . EnumOther::MINUS.',采购入库单删除',
 								'warehouse_id' => $trans['warehouse_id'],
 								'create_man' => Yii::$app->user->id,
 						];
 						$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 						if(! $res_log){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 						}
 						
 						//删除transaction 数据
 						$columns = [
 								'delete_flag'=>EnumOther::DELETED,
 						];
 						$conditions = "transaction_id = :tid";
 						$params = [
 								':tid'=>$trans['transaction_id'],
 						];
 						$trans_update = TransactionDAO::getInstance()->iupdate($columns, $conditions, $params);
 		
 						if(empty($trans_update)){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','tansaction del fail');
 						}
 						
 						// 更新stock_file 分仓表信息
 						$stock_minus = StockPileDAO::getInstance ()->updateAllCounters ( [
 								'quantity' => - $trans ['quantity']
 						], "warehouse_id =:wid and product_id=:pid and delete_flag =:flag", [
 								':wid' => $trans ['warehouse_id'],
 								':pid' => $trans ['goods_id'],
 								':flag' => EnumOther::NO_DELETE
 						] );
 						if(! $stock_minus){
 							$tT->rollBack ();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update stock pile quantity failure');
 						}
 						
 						//更新procurement
 						$result = ProcurementDAO::getInstance()->updateProcurement($trans['procurement_id'],$trans['procurement_det_id'],$trans['quantity']);
 						if(!$result){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update procurement failure');
 						}
 		
 					}
 				
 					
 				}

 			}
 			$tT->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tT->rollBack ();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 查询采购订单（导入订单）
 	 * @param $cond 查询条件
 	 * @param $pageInfo 页面信息
 	 * @author liaojianwen
 	 * @date 2016-12-19
 	 */
 	public function selectProcurement($cond, $pageInfo)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
		$result = ProcurementDAO::getInstance()->selectProcurement($cond, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
	}
	
	/**
	 * @desc 根据订单id 获取明细信息（导入订单）
	 * @author liaojianwen
	 * @date 2016-12-19
	 */
	public function getProDetail($id)
	{
		if (empty ( $id )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$fields = [ 
				'procurement_det_id',
				'd.procurement_id',
				'd.goods_id',
				'p.product_name',
				'p.product_sn',
				'd.quantity',
				'd.quantity_unit',
				'u.unit_name',
				'd.price',
				'd.amount',
				'd.remark',
				'd.minus_quantity',
				'd.received_quantity',
		];
		
		$joinArr = [ 
			[ 
				"product p",
				"p.product_id = d.goods_id",
			],
			[
				"unit u",
				"u.unit_id = d.quantity_unit",
			]
		];
		$conditions = "d.procurement_id = :id and d.delete_flag = :dflag and d.finish_flag =:fflag";
		$params = [ 
				':id' => $id,
				':dflag' => EnumOther::NO_DELETE,
				':fflag' => EnumOther::NO_FINISHED,
		];
 		$result = ProcurementDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"procurement_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail no data found');
		}
		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
	}
	/**
	 * @desc 检查订单是否被其他入库单占用
	 * @author liaojianwen
	 * @date 2016-12-20
	 */
	public function checkPurchaseById($id)
	{
		if(!$id){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
		$result = PurchaseDAO::getInstance ()->findByAttributes ( "purchase_id", "procurement_id =:pid and confirm_flag=:flag and delete_flag =:dflag", [ 
				':pid' => $id,
				':flag' => EnumOther::NO_CONFIRM ,
				':dflag' => EnumOther::NO_DELETE,
		] );
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 	}
	
	/**
	 * 获取采购入库明细
	 * @author liaojianwen
	 * @date 2016-12-29
	 */
	public function getPurchaseDet($id)
	{
		if (! $id) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$fields = [ 
				'purchase_det_id',
				'd.purchase_id',
				'd.goods_id',
				'p.product_name',
				'p.product_sn',
				'd.quantity',
				'd.quantity_unit',
				'u.unit_name',
				'd.price',
				'd.amount',
				'd.remark',
// 				'd.minus_quantity',
// 				'd.received_quantity' 
		];
		
		$joinArr = [ 
				[ 
						"product p",
						"p.product_id = d.goods_id" 
				],
				[ 
						"unit u",
						"u.unit_id = d.quantity_unit" 
				] 
		];
		$conditions = "d.purchase_id = :id and d.delete_flag = :dflag";
		$params = [ 
				':id' => $id,
				':dflag' => EnumOther::NO_DELETE,
		];
		$result = PurchaseDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"purchase_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	/**
 	 * @desc 按供应商统计应付单
 	 * @author liaojianwen
 	 * @date 2017-03-09
 	 */
 	public function getPurchaseCount($condition, $pageInfo)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','param is empty'); 
 		}
 		$result = PayablesDAO::getInstance()->getPurchaseCount($condition,$pageInfo);
 		if(!$result){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result); 
 	}
 	
 	/**
 	 * @desc 导出采购统计的信息
 	 * @author liaojianwen
 	 * @date 2017-03-10
 	 */
 	public function getPurchaseVendor($condition)
 	{
 		if(empty($condition)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'condition is null');
 		}
 		$result = PayablesDAO::getInstance()->getPurchaseVendor($condition);
 		if(!$result){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	/**
 	 * @desc 导出采购统计（供应商）
 	 * @author liaojianwen
 	 * @date 2017-03-10
 	 */
 	public function exportPurchaseVendor($purchaseInfo, $filename, $title, $excVer = "xls")
 	{
 		$data = $purchaseInfo['list'];
 		$objPHPExecl = new \PHPExcel();
 		$objSheet = $objPHPExecl->getActiveSheet();
 		$objWriter = NULL;
 		// 创建文件格式写入对象实例
 		switch ($excVer){
 			case 'xlsx':
 				$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExecl);
 				break;
 			case 'xls':
 				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
 				break;
 			default:
 				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
 		}
 		//设置宽度
 		$objSheet->mergeCells("A1:K2");
 		$objSheet->setCellValue("A1", $title);
 		$objSheet->getStyle('A1')->getFont()->setSize(26);
 		$objSheet->getStyle('A1')->getFont()->setBold(true);
 		$objSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 		
 		$i = 'A';
 		for ($n=0; $n<11; $n++) {
			$count = $i++;
 			$objSheet->getStyle($count.'2')->getBorders()->getBottom()->setBorderStyle(\PHPExcel_Style_Border::BORDER_DOUBLE);
 			$objSheet->getStyle($count.'7')->getBorders()->getBottom()->setBorderStyle(\PHPExcel_Style_Border::BORDER_DOUBLE);
 		}
 		
 		
 		///total
 		$objSheet->setCellValue("A4", '应付总金额：');
 		$objSheet->getStyle('A4')->getFont()->setSize(14);
 		$objSheet->getStyle('A4')->getFont()->setBold(true);
 		
 		$objSheet->setCellValue("A5", '已付总金额：');
 		$objSheet->getStyle('A5')->getFont()->setSize(14);
 		$objSheet->getStyle('A5')->getFont()->setBold(true);
 		
 		$objSheet->setCellValue("A6", '未付总金额');
 		$objSheet->getStyle('A6')->getFont()->setSize(14);
 		$objSheet->getStyle('A6')->getFont()->setBold(true);
 		
 		$objSheet->setCellValue("B4", $purchaseInfo['total_amount']);
 		$objSheet->getStyle('B4')->getFont()->setSize(14);
 		$objSheet->getStyle('B4')->getFont()->setBold(true);
 			
 		$objSheet->setCellValue("B5", $purchaseInfo['total_receive_amount']);
 		$objSheet->getStyle('B5')->getFont()->setSize(14);
 		$objSheet->getStyle('B5')->getFont()->setBold(true);
 			
 		$objSheet->setCellValue("B6", $purchaseInfo['total_left_amount']);
 		$objSheet->getStyle('B6')->getFont()->setSize(14);
 		$objSheet->getStyle('B6')->getFont()->setBold(true);
 		
 		$objSheet->setCellValue("C4", '元');
 		$objSheet->getStyle('C4')->getFont()->setSize(14);
 		$objSheet->getStyle('C4')->getFont()->setBold(true);
 			
 		$objSheet->setCellValue("C5", '元');
 		$objSheet->getStyle('C5')->getFont()->setSize(14);
 		$objSheet->getStyle('C5')->getFont()->setBold(true);
 			
 		$objSheet->setCellValue("C6", '元');
 		$objSheet->getStyle('C6')->getFont()->setSize(14);
 		$objSheet->getStyle('C6')->getFont()->setBold(true);
 		
 		
 		$objSheet->getColumnDimension('A')->setWidth(20);
 		$objSheet->getColumnDimension('B')->setWidth(20);
 		$objSheet->getColumnDimension('C')->setWidth(20);
 		$objSheet->getColumnDimension('D')->setWidth(20);
 		$objSheet->getColumnDimension('E')->setWidth(20);
 		$objSheet->getColumnDimension('F')->setWidth(20);
 		$objSheet->getColumnDimension('G')->setWidth(20);
 		$objSheet->getColumnDimension('H')->setWidth(20);
 		$objSheet->getColumnDimension('I')->setWidth(20);
 		$objSheet->getColumnDimension('J')->setWidth(20);
 		$objSheet->getColumnDimension('K')->setWidth(20);
 		$objSheet->setCellValue('A9', '日期');
 		$objSheet->getStyle('A9')->getFont()->setBold(true);
 		$objSheet->setCellValue('B9', '供应商');
 		$objSheet->getStyle('B9')->getFont()->setBold(true);
 		$objSheet->setCellValue('C9', '产品');
 		$objSheet->getStyle('C9')->getFont()->setBold(true);
 		$objSheet->setCellValue('D9', '单价');
 		$objSheet->getStyle('D9')->getFont()->setBold(true);
 		$objSheet->setCellValue('E9', '单位');
 		$objSheet->getStyle('E9')->getFont()->setBold(true);
 		$objSheet->setCellValue('F9', '总数量');
 		$objSheet->getStyle('F9')->getFont()->setBold(true);
 		$objSheet->setCellValue('G9', '应付总金额');
 		$objSheet->getStyle('G9')->getFont()->setBold(true);
 		$objSheet->setCellValue('H9', '已付数量');
 		$objSheet->getStyle('H9')->getFont()->setBold(true);
 		$objSheet->setCellValue('I9', '已付总金额');
 		$objSheet->getStyle('I9')->getFont()->setBold(true);
 		$objSheet->setCellValue('J9', '付款日期');
 		$objSheet->getStyle('J9')->getFont()->setBold(true);
 		$objSheet->setCellValue('K9', '未付总金额');
 		$objSheet->getStyle('K9')->getFont()->setBold(true);
		
 		$rowNum = 10;
 		foreach($data as $det){
 			$pay_date = $det['pay_time'] ? date('Y-m-d', $det['pay_time']) : '';
 			$receive_quantity = $det['left_amount'] > 0? 0 : $det['base_quantity'];
 			$receive_amount = $det['left_amount'] > 0? 0:$det['amount'];
 			$settle_pay_date = $det['settle_pay_date'] ? date('Y-m-d',$det['settle_pay_date']):'';
 			$left_amount = $det['left_amount']?:0;
 			$objSheet->setCellValue('K'.$rowNum, $left_amount);
 			
 			$this->_genExcelFont($objSheet, "A".$rowNum, "A".$rowNum, $pay_date, false);
 			$this->_genExcelFont($objSheet, "B".$rowNum, "B".$rowNum, $det['supplier_name'], false);
 			$this->_genExcelFont($objSheet, "C".$rowNum, "C".$rowNum, $det['product_name'], false);
 			$this->_genExcelFont($objSheet, "D".$rowNum, "D".$rowNum, $det['price'], false);
 			$this->_genExcelFont($objSheet, "E".$rowNum, "E".$rowNum, $det['unit_name'], false);
 			$this->_genExcelFont($objSheet, "F".$rowNum, "F".$rowNum, $det['base_quantity'], false);
 			$this->_genExcelFont($objSheet, "G".$rowNum, "G".$rowNum, $det['amount'], false);
 			$this->_genExcelFont($objSheet, "H".$rowNum, "H".$rowNum, $receive_quantity, false);
 			$this->_genExcelFont($objSheet, "I".$rowNum, "I".$rowNum, $receive_amount, false);
 			$this->_genExcelFont($objSheet, "J".$rowNum, "J".$rowNum, $settle_pay_date, false);
 			$this->_genExcelFont($objSheet, "K".$rowNum, "K".$rowNum, $left_amount, false);
 			
 			$rowNum++;
 		}
 		
 		ob_end_clean(); // 去掉缓存
 		header("Content-Type: application/force-download");
 		header("Content-Type: application/octet-stream");
 		header("Content-Type: application/download");
 		header('Content-Disposition:inline;filename="' . $filename . '.xls"');
 		header("Content-Transfer-Encoding: binary");
 		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
 		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 		header("Pragma: no-cache");
//  		            $objWriter->save("upload/demo.xlsx");
 		$objWriter->save('php://output');
 	}
 	
 	/**
 	 * @desc 导入采购订单
 	 * @author liaojianwen
 	 * @date 2017-05-02
 	 */
 	public function ImplodeProcurementInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$pro_head = ProcurementDAO::getInstance()->getProcurementHead($id);
 		if(empty($pro_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$pro_det = ProcurementDetailDAO::getInstance()->getProcurementDet($id);
 		if(empty($pro_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		foreach ($pro_det as &$det)
 		{
 			$det['left_quantity'] = $det['minus_quantity'];
 			foreach ( $det['product_unit'] as $unit){
 				if($det['quantity_unit'] == $unit['unit_id']){
 					$det['quantity_rate'] = $unit['rate'];
 					$det['quantity_name'] = $unit['unit_name'];
 				} 
 				if($det['second_unit'] == $unit['unit_id']){
 					$det['second_rate'] = $unit['rate'];
 					$det['second_name'] = $unit['unit_name'];
 				} 
 			}
 			
 			if($det['second_unit'] ){
 				 $det['second_quantity'] = $det['minus_quantity'] / $det['second_rate'];
 			}
 			
 			$det['quantity'] = $det['minus_quantity'] / $det['quantity_rate'];
 			$det['amount'] = round($det['quantity'] * $det['price'],2);
 			
 			if($det['second_unit'] ){
 				$tmp_name = floor($det ['quantity'] * $det ['quantity_rate'] / $det ['second_rate']);
				$tmp_content = fmod($det ['quantity']*$det['quantity_rate'],$det['second_rate']);
 				$det['second_relation'] = $tmp_name. $det['second_name'] .$tmp_content . $det['quantity_name'];
 			}
 			
 		}
 		$result['head'] = $pro_head;
 		$result['det'] = $pro_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	
 	/**
 	 * @desc 入库核算成本
 	 * @params $goods_id 商品id
 	 * @params $base_quantity 单据基本数量
 	 * @params $base_price  单据基本单价
 	 * @params $flag ture:入库  false ：出库
 	 * @params $order_type 单据类型
 	 * @author liaojianwen
 	 * @date 2018-02-09
 	 */
 	public function AccountingPrice($goods_id, $base_quantity, $base_price, $flag = true, $order_type = NULL)
 	{
 		$res = ProductDAO::getInstance()->iselect("accounting_method, price, quantity, is_accounting", "product_id =:gid", [':gid'=>$goods_id],'one');
 		if($res['accounting_method'] == 1){
 			//移动加权平均算法
 			if(!$res['is_accounting'] && $base_price == 0){
 				if($flag){//入库
 					$NowNum = $base_quantity;
 				} else {
 					$NowNum = - $base_quantity;
 				}
 				$NewPrice = $res['price']; // 商品价格为零不核算价格
 			} else {
	 			if($flag){//入库
	 				$tmp_quantity = $res['quantity'] + $base_quantity;
	 				if($tmp_quantity > 0){
	 					$NewPrice = ($res['price'] * $res['quantity'] + $base_price * $base_quantity) / $tmp_quantity;
	 				} else {
	 					$NewPrice = $res['price'];
	 				}
	 				$NowNum = $base_quantity;
	 			} else{
	 				//出库
	 				$left_quantity = $res['quantity']-$base_quantity;
	 				if($left_quantity){
	 					$NewPrice = ($res['price'] * $res['quantity'] - $base_price * $base_quantity) / $left_quantity;
	 				}else {
	 					$NewPrice = $res['price'];//先把出成零的，保存上次单价
	 				}
					$NowNum = - $base_quantity;
				}
				$res_price = ProductDAO::getInstance ()->iupdate ( [ 
						'price' => round($NewPrice,2) 
				], "product_id = :gid", [ 
						':gid' => $goods_id 
				] );
				
				// ProductDAO::getInstance()->iupdate(['stock_price' => $NewPrice], "goods_id", $params); //应该放在goods_quantity
				if (! $res_price) {
					return false;
				}
			}
			$columns_price = [ 
					'product_id' => $goods_id,
					'init_num' => $res ['quantity'],
					'init_price' => $res ['price'],
					'order_num' => $NowNum,
					'order_price' => $base_price,
					'create_time' => time (),
					'order_type' => $order_type,
					'user_id' => Yii::$app->user->id,
					'now_price' => round($NewPrice,2)
			];
			$res_price = AccountPriceLogDAO::getInstance ()->iinsert ( $columns_price, true );
			if (! $res_price) {
				return false;
			}
 		}
 		return true;
 	}
 }
 